package iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.activity.secondActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.R;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.entity.Product;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.entity.Trace;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.IProductService;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceConnection.ProductServiceConnection;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.service.serviceImpl.ProductService;
import iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.utils.ImageUtils;

public class ActivityModifyProduct extends AppCompatActivity {
    private EditText editProductName, editCategory, editPrice, editProduceDate;
    private Button btnSubmit, btnBack;
    private ImageView productImage,addIcon;
    private Product product;
    private ProductServiceConnection productConnection;
    private SharedPreferences sharedPreferences;
    private FrameLayout imageFrame;

    // 拍照相关变量
    private Uri photoUri;
    private ActivityResultLauncher<Uri> takePhotoLauncher;
    private static final int REQUEST_CAMERA_PERMISSION = 100;
    private static final int REQUEST_STORAGE_PERMISSION = 101;

    @Override
    protected void onStart() {
        super.onStart();
        productConnection = new ProductServiceConnection(service -> {});
        Intent intent = new Intent(this, ProductService.class);
        bindService(intent, productConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (productConnection != null && productConnection.isBound()) {
            unbindService(productConnection);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_product);


        // 初始化视图组件
        editProductName = findViewById(R.id.editProductName);
        editCategory = findViewById(R.id.editCategory);
        editPrice = findViewById(R.id.editPrice);
        editProduceDate = findViewById(R.id.editProduceDate);
        btnSubmit = findViewById(R.id.btnSubmit);
        btnBack = findViewById(R.id.btnBack);
        productImage = findViewById(R.id.user_image);
        addIcon = findViewById(R.id.icon_add);
        imageFrame = findViewById(R.id.image_frame);

        init();



        // 提交按钮
        btnSubmit.setOnClickListener(v -> setBtnSubmit());

        // 返回按钮点击事件
        btnBack.setOnClickListener(v -> {
            // 点击返回按钮时结束当前活动，返回前一个页面
            setResult(RESULT_CANCELED);  // 如果用户取消了更新，返回失败结果
            finish();  // 结束当前活动并返回
        });



    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == this.RESULT_OK && data != null) {
                Uri selectedImageUri = data.getData(); // 获取选中图片的URI
                productImage.setImageURI(selectedImageUri);
                productImage.setVisibility(View.VISIBLE); // 显示 ImageView
                addIcon.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onBackPressed() {
        // 当点击设备的返回按钮时，返回前一个页面
        setResult(RESULT_CANCELED);  // 如果用户取消了更新，返回失败结果
        super.onBackPressed();
    }


    private void setBtnSubmit(){

        // 获取用户输入的更新数据
        String updatedProductName = editProductName.getText().toString();
        String updatedCategory = editCategory.getText().toString();
        double updatedPrice = Double.parseDouble(editPrice.getText().toString());
        String updatedProduceDate = editProduceDate.getText().toString();
        product.setProductName(updatedProductName);
        product.setCategory(updatedCategory);
        product.setPrice(updatedPrice);
        product.setProduceDate(updatedProduceDate);
        // 使用绑定的服务更新产品信息
        if (productConnection.getService() != null && productConnection.getService() .updateProductInfo(product)) {
            Toast.makeText(this, "产品更新成功", Toast.LENGTH_SHORT).show();
            setResult(RESULT_OK);  // 返回更新成功的结果
            finish();  // 结束当前活动
        } else {
            Toast.makeText(this, "更新失败", Toast.LENGTH_SHORT).show();
        }


        if (product.getImage() == null && productImage.getDrawable() != null) {
            Trace trace = new Trace();
            Bitmap bitmap = ImageUtils.drawable2bitmap(productImage.getDrawable());
            trace.setProductId(product.getProductId());
            trace.setProducerId(sharedPreferences.getInt("userId",-1));
            trace.setProducerImg(ImageUtils.bitmap2Blob(bitmap));
            productConnection.getService().addTraceabilityPicture(trace,0);
        }
    }


    // 图片步骤1 选择菜单监听
    private void showImageSelectionMenu() {
        String[] options = {"拍摄照片", "从图库选择"};
        new AlertDialog.Builder(this)
                .setTitle("选择图片来源")
                .setItems(options, (dialog, which) -> {
                    if (which == 0) {
                        takePhoto(); // 拍照
                    } else if (which == 1) {
                        openImagePicker(); // 从图库选择
                    }
                })
                .show();
    }
    // 图片步骤2.1 拍照选择
    private void takePhoto() {
        // 确保在调用摄像头之前检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            // 创建临时文件的 URI
            File tempFile;
            try {
                // 创建用于存储照片的临时文件
                File storageDir = this.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                tempFile = File.createTempFile("photo_", ".jpg", storageDir);
                photoUri = FileProvider.getUriForFile(
                        this,
                        this.getPackageName() + ".fileprovider",
                        tempFile
                );
                takePhotoLauncher.launch(photoUri);
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "无法创建临时文件", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "请先授予相机权限", Toast.LENGTH_SHORT).show();
        }
    }
    // 图片步骤2.2 图库选择
    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*"); // 只显示图片类型的文件
        startActivityForResult(intent, 1); // 请求码为1
    }





    // 初始化
    private void init(){
        // 初始化拍照功能
        requestPermissions();
        initTakePhotoLauncher();

        productConnection = new ProductServiceConnection(service -> {

            // 获取传递的产品信息
            String info = getIntent().getStringExtra("productId");
            Log.d("Test",info);
            product = service.getProductInfoById(info);
            Log.d("Test",product.toString());



            sharedPreferences = getSharedPreferences("ACCOUNT_REMEMBER", MODE_PRIVATE);


            editProductName.setText(product.getProductName());
            editCategory.setText(product.getCategory());
            editPrice.setText(product.getPrice().toString());
            editProduceDate.setText(product.getProduceDate());
            if (product.getImage() != null) {
                productImage.setImageBitmap(ImageUtils.blob2Bitmap(product.getImage()));
                productImage.setVisibility(View.VISIBLE); // 显示 ImageView
                addIcon.setVisibility(View.GONE);
            }


            // 选择图片来源按钮
            if (product.getImage() == null){
                imageFrame.setOnClickListener(v -> showImageSelectionMenu());
            }else {
                imageFrame.setOnClickListener(v -> {
                    Toast.makeText(this, "图片无法更改", Toast.LENGTH_SHORT).show();
                });
            }
        });

        Intent intent = new Intent(this, ProductService.class);
        bindService(intent, productConnection, BIND_AUTO_CREATE);

    }
    // 初始化摄像步骤0 获取权限
    private void requestPermissions() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION);
        }
    }
    // 初始化摄像步骤1
    private void initTakePhotoLauncher() {
        takePhotoLauncher = registerForActivityResult(
                new ActivityResultContracts.TakePicture(),
                success -> {
                    if (success && photoUri != null) {
                        showPhoto(); // 在成功拍照后显示照片
                    } else {
                        Toast.makeText(this, "拍照失败", Toast.LENGTH_SHORT).show();
                    }
                }
        );
    }
    // 初始化摄像步骤2
    private void showPhoto() {
        if (photoUri != null) {
            try {
                // 从 Uri 创建输入流并解码 Bitmap
                InputStream inputStream = this.getContentResolver().openInputStream(photoUri);
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                if (bitmap != null) {
                    productImage.setImageBitmap(bitmap);
                    productImage.setVisibility(View.VISIBLE); // 显示 ImageView
                    addIcon.setVisibility(View.GONE);
                } else {
                    Toast.makeText(this, "无法解码图片", Toast.LENGTH_SHORT).show();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                Toast.makeText(this, "文件未找到", Toast.LENGTH_SHORT).show();
            }
        }
    }
}



